<?php

namespace app\admin\controller\exam;

use app\admin\model\exam\CateModel;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;

/**
 * 试题
 * @icon fa fa-circle-o
 */
class Question extends Backend
{

    /**
     * QuestionModel模型对象
     * @var \app\admin\model\exam\QuestionModel
     */
    protected $model = null;
    protected $noNeedRight = ['*'];
    protected $multiFields = 'status';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\exam\QuestionModel;
        $this->view->assign("kindList", $this->model->getKindList());
        $this->view->assign("difficultyList", $this->model->getDifficultyList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['cate'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('cate')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            // if ($params['options_extend']) {
            //     $params['options_extend'] = json_decode(urldecode($params['options_extend']), true);
            // }
            // dd($params);
            if ($params) {
                $params = $this->preExcludeFields($params);

                // 检查题目输入
                $this->checkTitle($params);
                // 检查答案输入
                $this->checkAnswer($params);
                // 处理选项图片链接域名
                $this->optionsImage($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                // 检查题目输入
                $this->checkTitle($params);
                // 检查答案输入
                $this->checkAnswer($params);
                // 处理选项图片链接域名
                $this->optionsImage($params);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function view($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $this->view->assign("row", $row);
        $options_json = json_decode($row['options_json'],true);
        // dump($options_json);exit;
        $this->view->assign("options_json", $options_json);
        return $this->view->fetch();
    }
    /**
     * 选项图片页面
     * @return string
     */
    public function image()
    {
        if ($this->request->isPost()) {
            $this->success($this->request->post());
        }
        return $this->view->fetch();
    }

    /**
     * 试题导入
     */
    public function importExcel()
    {
        if ($this->request->isPost()) {
            // parent::import();
            $cate = $this->request->param('cate');
            // $exam_type = $this->request->param('exam_type');
            if (!$cate) { //  || !$exam_type
                $this->error('请先选择所属类型及考试分类再进行上传');
            }
            $cname = Db::table('fa_exam_question_file')->where(['id'=>1])->value('name');
            $data = [
                'parent_id' => $cate,
                'kind' => 'QUESTION',
                'level' => 4,
                'name' => $cname,
            ];
            $clist = Db::table('fa_exam_cate')->where($data)->find();
            if(empty($clist))
            {
                $cate = Db::table('fa_exam_cate')->insertGetId($data);
            }
            else
            {
                $cate = $clist['id'];
            }

            $file = $this->request->request('file');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }

            $filePath = ROOT_PATH . DS . 'public' . DS . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }

            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }

            if ($ext === 'csv') {
                $file     = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp       = fopen($filePath, "w");
                $n        = 0;
                while ($line = fgets($file)) {
                    $line     = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            //加载文件
            $insert = [];
            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    throw new \Exception(__('Unknown data format'));
                }
                $currentSheet    = $PHPExcel->getSheet(0);                //读取文件中的第一个工作表
                $allColumn       = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow          = $currentSheet->getHighestRow();        //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                $fields          = [
                    'kind',
                    'title',
                    'explain',
                    'difficulty',
                    'answer',
                    'A',
                    'B',
                    'C',
                    'D',
                    'E',
                    'F',
                    'G',
                    'H',
                ];

                for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : $val;

                    }
                    // $temp    = array_combine($fields, $values);
                    $row     = [];
                    $options = [];

                    // 选项及字段组合
                    for ($i = 0; $i < min($maxColumnNumber, count($fields)); $i++) {
                        $field = $fields[$i];
                        $value = $values[$i];

                        if ($i > 4) {
                            if (!empty($value) || $value == '0') {
                                $options[$field] = $value;
                            }
                        } else {
                            $row[$field] = $value;
                        }
                    }

                    // 过滤空行
                    if (!$row['title']) {
                        continue;
                    }

                    // 特殊字段处理
                    foreach ($row as $key => $item) {
                        if ($key == 'kind') {
                            switch ($item) {
                                case '判断':
                                case '判断题':
                                    $item = 'JUDGE';
                                    break;
                                case '单选':
                                case '单选题':
                                    $item = 'SINGLE';
                                    break;
                                case '多选':
                                case '多选题':
                                    $item = 'MULTI';
                                    break;
                                case '填空':
                                case '填空题':
                                    $item = 'FILL';
                                    break;
                            }
                        } else if ($key == 'difficulty') {
                            switch ($item) {
                                case '低':
                                case '简单':
                                    $item = 'EASY';
                                    break;
                                case '高':
                                case '困难':
                                    $item = 'HARD';
                                    break;
                                default:
                                    $item = 'GENERAL';
                                    break;
                            }
                        }

                        $row[$key] = $item;
                    }

                    // 判断题特殊情况处理
                    if ($row['kind'] == 'JUDGE') {
                        switch ($row['answer']) {
                            case '正确':
                            case '对':
                                $row['answer'] = 'A';
                                break;
                            case '错误':
                            case '错':
                                $row['answer'] = 'B';
                                break;
                        }

                        $options = $options ? $options : ['A' => '正确', 'B' => '错误'];
                    }

                    // 答案特殊处理
                    $row['answer'] = str_replace(' ', '', $row['answer']);
                    $row['answer'] = str_replace(' ', '', $row['answer']);
                    $row['answer'] = str_replace('，', ',', $row['answer']);

                    if (!$row['answer'] || ($row['kind'] == 'MULTI' && !strpos($row['answer'], ','))) {
                        throw new \Exception('题目【' . $row['title'] . '】答案格式有误');
                    }
                    // 填空题
                    if ($row['kind'] == 'FILL') {
                        $row['answer'] = explode('|||', $row['answer']);
                        $fill_count    = count(explode('______', $row['title'])) - 1;
                        $answer_count  = count($row['answer']);

                        if ($fill_count != $answer_count) {
                            throw new \Exception('题目【' . $row['title'] . '】填空位与答案数量不匹配');
                        }

                        $fill_answers = [];
                        foreach ($row['answer'] as $item) {
                            $fill_answers[] = ['answers' => explode(',', $item)];
                        }

                        $row['answer'] = json_encode($fill_answers, JSON_UNESCAPED_UNICODE);
                    }

                    $row['options_json'] = json_encode($options, JSON_UNESCAPED_UNICODE);
                    $row['cate_id']      = $cate;
                    // $row['exam_type_id'] = $exam_type;
                    $insert[] = $row;
                }

                Session::set('import_question', $insert);
            } catch (\Exception $exception) {
                $this->error($exception->getMessage());
            }

            if (!$insert) {
                $this->error(__('No rows were updated'));
            }
            // return json($insert);
            $this->success('识别成功', '', ['count' => count($insert)]);
        }
        $this->error('错误的提交方式');
    }

    /**
     * 试题导入提交
     * @return string|void
     */
    public function import()
    {

        if ($this->request->isPost()) {

            // 加载数据
            $insert = Session::pull('import_question');
            if (!$insert) {
                $this->error(__('没有可以导入的数据，请重新上传Excel文件'));
            }

            try {
                $this->model->saveAll($insert);
            } catch (PDOException $exception) {
                $msg = $exception->getMessage();
                if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                    $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
                };
                $this->error($msg);
            } catch (\Exception $exception) {
                $this->error($exception->getMessage());
            }

            $this->success();
        }
        $where = [
            'parent_id' => 0,
            'kind' => 'QUESTION',
            'deletetime' => null
        ];
        $clist = Db::table('fa_exam_cate')->where($where)->order('sort asc')->select();

        $this->view->assign("clist", $clist);

        //如果又分类id查询分类信息
        $cate_id = $this->request->get('cate_id');
        $return = [
            'parent_id1' => '',
            'parent_id2' => '',
            'parent_id3' => '',
            'parent_id4' => '',
            'parent_list2' => [],
            'parent_list3' => [],
            'parent_list4' => [],
        ];
        if ($cate_id) {
            $this->getCategory($cate_id, $return);
        }
        $this->view->assign('categoryList',$return);
        return $this->view->fetch();
    }
    public function get_qcate()
    {
        if ($this->request->isAjax())
        {
            $cid = $this->request->request('cid');
            $where = [
                'parent_id' => $cid,
                'kind' => 'QUESTION',
                'deletetime' => null
            ];
            $clist = Db::table('fa_exam_cate')->where($where)->order('sort asc')->select();

            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => ['list'=>$clist],
            ];
            return json($result);
        }
    }

    /**
     * 获取题库数量
     */
    public function getCount()
    {
        $cate_ids = $this->request->param('cate_ids');

        if (!$cate_ids) {
            $this->error('请先选择题库');
        }

        $this->success('', '', $this->model->getCount($cate_ids));
    }

    /**
     * 选择题目页面
     */
    public function select()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['cate'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('cate')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function test()
    {
        $this->success('', '', Session::get('import_question'));
    }

    /**
     * 检查答案输入
     * @param $params
     */
    protected function checkAnswer(&$params)
    {
        $answer  = $params['answer'] ?? '';
        $options = $params['options_json'] ?? [];

        if (in_array($params['kind'], ['MULTI', 'JUDGE', 'SINGLE'])) {
            if (!$answer) {
                $this->error('请设置题目答案');
            }
            if (!$options) {
                $this->error('请设置题目选项');
            }

            $options     = json_decode($options, true);
            $option_keys = array_keys($options);

            // 多选题
            if (strpos($answer, ',') !== false) {
                $answer_arr = explode(',', trim($answer));
                foreach ($answer_arr as $item) {
                    if (!in_array($item, $option_keys)) {
                        $this->error('答案设置有误，答案选项不存在');
                    }
                }
            } else {
                if (!in_array($answer, $option_keys)) {
                    $this->error('答案设置有误，答案选项不存在');
                }
            }
        }

        // 后期拓展题型
        switch ($params['kind']) {
            // 填空题
            case 'FILL':
                if (!is_array($answer) || !count($answer)) {
                    $this->error('未设置填空题答案，至少设置一个');
                }

                // 扩展格式
                // $params['options_extend'] = [];
                // for ($i = 0; $i < count($params['answer']); $i++) {
                //     $params['options_extend'][] = [
                //         'user_answer' => '',
                //     ];
                // }
                // $params['options_extend'] = json_encode($params['options_extend']);

                // 转json
                $params['answer'] = json_encode($params['answer'], JSON_UNESCAPED_UNICODE);
                break;
        }
    }

    /**
     * 处理选项图片链接域名
     * @param $data
     */
    protected function optionsImage(&$data)
    {
        $options_img = $data['options_img'] ?? [];
        $options_img = json_decode($options_img, true);
        if ($options_img) {
            foreach ($options_img as &$item) {
                if (strpos($item['value'], '://') === false) {
                    $item['value'] = cdnurl($item['value'], true);
                }
            }
        }
        $data['options_img'] = json_encode($options_img);
        $data['options_img'] = $data['options_img'] == 'null' ? [] : $data['options_img'];
    }

    /**
     * 检查题目内容输入
     * @param $params
     */
    protected function checkTitle(&$params)
    {
        if (in_array($params['kind'], ['MULTI', 'JUDGE', 'SINGLE'])) {
            if (!($params['title'] ?? '')) {
                $this->error('请输入题目内容');
            }
        } else if ($params['kind'] == 'FILL') {
            if (!($params['title_fill'] ?? '')) {
                $this->error('请输入填空题题目内容');
            }
            $params['title'] = $params['title_fill'];
        }
    }
    /**
     * 试题分配
     * auth:zlq
     * data:2023.09.07
     * sql:INSERT INTO `xdzs_tswm_club`.`fa_auth_rule`(`id`, `type`, `pid`, `name`, `title`, `icon`, `url`, `condition`, `remark`, `ismenu`, `menutype`, `extend`, `py`, `pinyin`, `createtime`, `updatetime`, `weigh`, `status`) VALUES (NULL, 'file', 85, 'exam/question/allocation', '试题分配', 'fa fa-question-circle-o', '', '', '', 1, NULL, '', 'stfp', 'shitifenpei', 1694075580, 1694075580, 0, 'normal')
     * ALTER TABLE `xdzs_tswm_club`.`fa_exam_question`
    ADD COLUMN `describe` text NULL COMMENT '简介' AFTER `admin_id`;
     */
    public function allocation()
    {
        $where = [
            'kind' => 'QUESTION',
            'level' => 1,
            'deletetime' => null
        ];
        $list = Db::table('fa_exam_cate')->where($where)->order('sort asc')->select();
        $tkwhere = [
            'status' => 1
        ];
        $tklist = Db::table('fa_classes_tiku')->where($tkwhere)->order('weigh desc')->select();
        $this->assign('list', $list);
        $this->assign('tklist', $tklist);

        //如果又分类id查询分类信息
        $cate_id = $this->request->get('cate_id');
        $return = [
            'parent_id1' => '',
            'parent_id2' => '',
            'parent_id3' => '',
            'parent_id4' => '',
            'parent_list2' => [],
            'parent_list3' => [],
            'parent_list4' => [],
        ];
        if ($cate_id) {
            $this->getCategory($cate_id, $return);
        }
        $this->view->assign('categoryList',$return);
        return $this->view->fetch();
    }

    /**
     * 获取分类数据
     */
    public function getCategory($cate_id, &$return)
    {
        $cate = CateModel::where('id', $cate_id)->field('id,level,name,parent_id')->find()->toArray();
        $return['parent_id'.$cate['level']] = $cate_id;
        if ($cate && $cate['parent_id'] != 0) {
            $return['parent_id'.($cate['level']-1)] = $cate['parent_id'];
            $return['parent_list'.$cate['level']] = CateModel::where('parent_id', $cate['parent_id'])->field('id,level,name,parent_id')->select();
            $this->getCategory($cate['parent_id'], $return);
            return ;
        }
        $return['parent_list2'] = CateModel::where('parent_id', $cate['id'])->field('id,level,name,parent_id')->select();
    }

    /**
     * 获取试题列表
     * auth:zlq
     * data:2023.09.08
     */
    public function get_question()
    {
        if ($this->request->isAjax())
        {

            $cid = $this->request->request('cid');
            $where = [
                'cate_id' => $cid,
                'deletetime' => null
            ];
            $list = Db::table('fa_exam_question')->field('id')->where($where)->order('id asc')->select();

            if (!empty($list))
            {
                $number = count($list);
                $cwhere = [ 'id' => $cid ];
                $clist = Db::table('fa_exam_cate')->field('name')->where($cwhere)->find();
                foreach ($list as $k => $v)
                {
                    $num = $k+1;
                    if($num < 10)
                    {
                        $num = '0'.$num;
                    }
                    $list[$k]['name'] = $clist['name'] . ' - ' . $num;
                }
                $where1 = [
                    'parent_id' => $cid,
                    'kind' => 'QUESTION',
                    'deletetime' => null
                ];
                $clist1 = Db::table('fa_exam_cate')->where($where1)->order('sort asc')->select();
                if(!empty($clist1))
                {
                    $list1 = $clist1;
                }
                else
                {
                    $list1 = [];
                }

                $result = [
                    'msg' => 'success',
                    'code' => 100,
                    'data' => $list,
                    'num' => $number,
                    'list' => $list1
                ];
            }
            else
            {
                $where1 = [
                    'parent_id' => $cid,
                    'kind' => 'QUESTION',
                    'deletetime' => null
                ];
                $clist1 = Db::table('fa_exam_cate')->where($where1)->order('sort asc')->select();
                if(!empty($clist1))
                {
                    $list1 = $clist1;
                }
                else
                {
                    $list1 = [];
                }
                $result = [
                    'msg' => 'success',
                    'code' => 101,
                    'data' => $list,
                    'num' => 0,
                    'list' => $list1
                ];
            }

            return json($result);
        }
    }
    /**
     * 获取单个试题
     * auth:zlq
     * data:2023.09.08
     */
    public function get_view()
    {
        if ($this->request->isAjax())
        {
            $qid = $this->request->request('qid');

            $row = $this->model->get($qid);

            if (!$row) {
                $this->error(__('No Results were found'));
            }
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                if (!in_array($row[$this->dataLimitField], $adminIds)) {
                    $this->error(__('You have no permission'));
                }
            }
            $data = array();
            switch ($row['kind']) {
                case 'SINGLE':
                    $data['kind'] = '单选题';
                    break;
                case 'JUDGE':
                    $data['kind'] = '判断题';
                    break;
                case 'MULTI':
                    $data['kind'] = '多选题';
                    break;
                case 'FILL':
                    $data['kind'] = '填空题';
                    break;
                default:
                    $data['kind'] = '单选题';
            }
            switch ($row['difficulty']) {
                case 'EASY':
                    $data['difficulty'] = '简单';
                    break;
                case 'GENERAL':
                    $data['difficulty'] = '普通';
                    break;
                case 'MULTI':
                    $data['HARD'] = '困难';
                    break;
                default:
                    $data['difficulty'] = '单选题';
            }
            $data['describe'] = $row['describe'];
            $data['title'] = $row['title'];
            $data['answer'] = $row['answer'];
            $data['id'] = $row['id'];
            $data['other_url'] = $row['other_url'];
            $data['other_url2'] = $row['other_url2'];
            $data['other_url3'] = $row['other_url3'];
            $data['other_name'] = $row['other_name'];
            $data['other_name2'] = $row['other_name2'];
            $data['other_name3'] = $row['other_name3'];

            $options_json = json_decode($row['options_json'], true);
            $data['options_json'] = $options_json;

            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => $data,
            ];
            return json($result);
        }
    }
    /**
     * iframe加载
     * auth:zlq
     * data:2023.09.08
     */
    public function get_views($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $this->view->assign("row", $row);
        $options_json = json_decode($row['options_json'],true);
        // dump($options_json);exit;
        $this->view->assign("options_json", $options_json);
        return $this->view->fetch();
    }
    /**
     * 分配题库
     * auth:zlq
     * data:2023.09.08
     */
    public function fptk()
    {
        if ($this->request->isAjax())
        {
            $ids = $this->request->request('ids');
            $describe = $this->request->request('describe');
            $tkid = $this->request->request('tkid');
            $other_url = $this->request->request('other_url');
            $other_name = $this->request->request('other_name');

            $id_arr = explode(',',$ids);

            $json_arr = array();

            $tklist = Db::table('fa_classes_tiku')->where(['id'=>$tkid])->find();
            $questions = $tklist['questions'];

            if(!empty($questions))
            {
                $questions_arr = json_decode($questions,true);

                foreach ($questions_arr as $kk => $vv)
                {
                    if(!in_array($vv['id'],$id_arr))
                    {
                        $id_arr[] = $vv['id'];
                    }
                }
            }

            foreach ($id_arr as $k => $v)
            {
                if (empty($v))
                {
                    unset($id_arr[$k]);
                }
                else
                {
                    $json_arr[$k]['id'] = $v;
                    $json_arr[$k]['score'] = 1;
                }

            }

            $json_arr = json_encode($json_arr);

            Db::table('fa_exam_question')->where('id','in',$ids)->update(['describe'=>$describe,'other_url'=>$other_url,'other_name'=>$other_name]);

//            Db::table('fa_classes_tiku')->where(['id'=>$tkid])->update(['questions'=>$json_arr]);

            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => [],
            ];
            return json($result);
        }
    }
    /**
     * 删除
     * auth:zlq
     * data:2023.09.14
     */
    public function qdel()
    {
        if ($this->request->isAjax())
        {
            $qid = $this->request->request('del_id');
            $list = Db::table('fa_exam_question')->where('id', $qid)->find();
            if (!empty($list))
            {
                Db::table('fa_exam_question')->where('id', $qid)->update(['deletetime' => time()]);
                $result = [
                    'msg' => 'success',
                    'code' => 100,
                    'data' => ['cate_id' => $list['cate_id']],
                ];
                return json($result);
            }
        }
    }
    /**
     * 随机分配
     * auth:zlq
     * data:2023.09.14
     */
    public function sjfp()
    {
        if ($this->request->isAjax())
        {
            $qid = $this->request->request('qid');
            $tkid = $this->request->request('tkid');
            $shu_num = $this->request->request('shu_num');
            $describe = $this->request->request('describe');
            $other_url = $this->request->request('other_url');

            $qlist = Db::table('fa_exam_question')->where('id', $qid)->find();

            $where = [
                'cate_id' => $qlist['cate_id'],
                'deletetime' => null
            ];
            $count = Db::table('fa_exam_question')->where($where)->count();

            if ($shu_num == 0)
            {
                $result = [
                    'msg' => 'success',
                    'code' => 100,
                    'data' => [],
                ];
                return json($result);
            }
            elseif ($shu_num >= $count)
            {
                $list = Db::table('fa_exam_question')->where($where)->select();
            }
            elseif ($shu_num < $count)
            {
                $list = Db::table('fa_exam_question')->where($where)->orderRaw("RAND()")->limit($shu_num)->select();
            }

            $json_arr = array();
            $ids = '';
            foreach ($list as $k => $v)
            {
                $json_arr[$k]['id'] = $v['id'];
                $json_arr[$k]['score'] = 1;
                $ids .= $v['id'] . ',';
            }
            $ids = trim($ids,',');
            $json_arr = json_encode($json_arr);

            Db::table('fa_exam_question')->where('id', 'in', $ids)->update(['describe' => $describe,'other_url'=>$other_url]);

//            Db::table('fa_classes_tiku')->where(['id' => $tkid])->update(['questions' => $json_arr]);

            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => [],
            ];
            return json($result);
        }
    }
    //2024.1.5保存
    public function subb()
    {
        if ($this->request->isAjax())
        {
            $qid = $this->request->request('qid');
            $describe = $this->request->request('describe');
            $other_url = $this->request->request('other_url');
            $other_url2 = $this->request->request('other_url2');
            $other_url3 = $this->request->request('other_url3');
            $other_name = $this->request->request('other_name');
            $other_name2 = $this->request->request('other_name2');
            $other_name3 = $this->request->request('other_name3');

            $qlist = Db::table('fa_exam_question')->where('id', $qid)->find();

            $where = [
                'cate_id' => $qlist['cate_id'],
                'deletetime' => null
            ];

            Db::table('fa_exam_question')->where($where)->update(['describe' => $describe, 'other_url' => $other_url, 'other_url2' => $other_url2, 'other_url3' => $other_url3, 'other_name' => $other_name, 'other_name2' => $other_name2, 'other_name3' => $other_name3]);

            $result = [
                'msg' => 'success',
                'code' => 100,
                'data' => [],
            ];
            return json($result);
        }
    }
    public function qtest()
    {
        /*$url = 'https://mp.weixin.qq.com/s/93VzLUisfKPxo91G63qEqA';
        $html = file_get_contents($url);
        $html = iconv('gb2312','utf-8//IGNORE',$html);
        preg_match("/<title>(.*?)<\/title>/i",$html,$matches);
        $title =$matches[1];
        dump($title);*/
        /*$url = 'https://mp.weixin.qq.com/s/93VzLUisfKPxo91G63qEqA';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        $html = curl_exec($ch);
        curl_close($ch);
        dump($html);*/
        $db2 = Db::connect('db2');
        $list = $db2->table('fa_admin')->select();
        dump($list);die;
    }
}
